package com.bringspring.extend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bringspring.common.util.DateUtil;
import com.bringspring.common.util.RandomUtil;
import com.bringspring.common.util.UserProvider;
import com.bringspring.extend.entity.ScheduleEntity;
import com.bringspring.extend.mapper.ScheduleMapper;
import com.bringspring.extend.service.ScheduleService;
import com.bringspring.system.base.entity.MessageTemplateEntity;
import com.bringspring.system.base.service.MessageTemplateService;
import com.bringspring.system.base.service.SysConfigService;
import com.bringspring.system.message.model.message.SentMessageForm;
import com.bringspring.workflow.engine.util.ServiceAllUtil;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 日程安排
 *
 * @author 开发平台组
 * @version V1.0.0
 * @copyright 股份有限公司
 * @date 2017年9月26日 上午9:18
 */
@Service
public class ScheduleServiceImpl extends ServiceImpl<ScheduleMapper, ScheduleEntity> implements ScheduleService {

    @Autowired
    private UserProvider userProvider;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private ServiceAllUtil serviceUtil;

    @Override
    public List<ScheduleEntity> getList(String startTime, String endTime) {
        QueryWrapper<ScheduleEntity> queryWrapper = new QueryWrapper<>();
        Date startTimes = DateUtil.stringToDates(startTime);
        Date endTimes = DateUtil.stringToDates(endTime);
        queryWrapper.lambda().eq(ScheduleEntity::getCreatorUserId, userProvider.get().getUserId())
                .ge(ScheduleEntity::getStartTime, startTimes)
                .le(ScheduleEntity::getEndTime, endTimes)
                .orderByAsc(ScheduleEntity::getCreatorTime);
        return this.list(queryWrapper);
    }

    @Override
    public List<ScheduleEntity> getListByTimeScoped(String startTime, String endTime) {
        QueryWrapper<ScheduleEntity> queryWrapper = new QueryWrapper<>();
        Date startTimes = DateUtil.stringToDate(startTime);
        Date endTimes = DateUtil.stringToDate(endTime);
         queryWrapper.lambda()
                .ge(ScheduleEntity::getStartTime, startTimes)
                .le(ScheduleEntity::getEndTime, endTimes)
                .orderByAsc(ScheduleEntity::getCreatorTime);
        return this.list(queryWrapper);
    }

    @Override
    public List<ScheduleEntity> getListByTimeScopedAndUserId(String startTime, String endTime) {
        QueryWrapper<ScheduleEntity> queryWrapper = new QueryWrapper<>();
        Date startTimes = DateUtil.stringToDate(startTime);
        Date endTimes = DateUtil.stringToDate(endTime);
        queryWrapper.lambda().eq(ScheduleEntity::getCreatorUserId, userProvider.get().getUserId())
                .ge(ScheduleEntity::getStartTime, startTimes)
                .le(ScheduleEntity::getEndTime, endTimes)
                .orderByAsc(ScheduleEntity::getCreatorTime);
        return this.list(queryWrapper);
    }

    @Override
    public ScheduleEntity getInfo(String id) {
        QueryWrapper<ScheduleEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ScheduleEntity::getId, id);
        return this.getOne(queryWrapper);
    }

    @Override
    public void delete(ScheduleEntity entity) {
        this.removeById(entity.getId());
    }

    @Override
    public void create(ScheduleEntity entity) {
        entity.setId(RandomUtil.uuId());
        entity.setCreatorUserId(userProvider.get().getUserId());

        this.save(entity);
    }

    @Override
    public Boolean judgeScheduleTimeConflict(ScheduleEntity entity) {
        String s = DateUtil.dateFormatToDay(DateUtil.getNowDate(), "yyyy-MM-dd");
        List<ScheduleEntity> list = this.getListByTimeScopedAndUserId(s + " 00:00:00", s + " 23:59:59");
        if (!list.isEmpty()) {
            for (ScheduleEntity scheduleEntity : list) {
                boolean b = DateUtil.hasOverlap(scheduleEntity.getStartTime(), scheduleEntity.getEndTime(), entity.getStartTime(), entity.getEndTime());
                if (b) {
                    return b;
                }
            }
        }
        return false;
    }

    @Override
    public boolean update(String id, ScheduleEntity entity) {
        entity.setId(id);
        entity.setLastModifyTime(new Date());
        entity.setLastModifyUserId(userProvider.get().getUserId());
        return this.updateById(entity);
    }

    /**
     * 发送站内信  企业微信
     *
     * @param userId
     * @param title
     * @param content
     * @param content
     * @throws
     */
    @Override
    public void sendMessage(List<String> userId, String title, String content, String url) throws Exception {
        List<String> collect = userId.stream().distinct().collect(Collectors.toList());
        SentMessageForm sentMessageForm = new SentMessageForm();
        sentMessageForm.setType(50);
        sentMessageForm.setToUserIds(collect);
        sentMessageForm.setTemplateId(sysConfigService.getConfigByKeyName("scheduleMessage").getKeyValue());

        sentMessageForm.setTitle("站内信标题");
        sentMessageForm.setContent("站内信内容");
        sentMessageForm.setBodyText(new HashMap<>());
        Map<String, String> map = new HashMap<>();
        map.put("title", title);
        map.put("content", content);
        map.put("AppUrl", sysConfigService.getConfigByKeyName("qyhMobileUrl").getKeyValue() + url);
        // 关联产品
        sentMessageForm.setParameterMap(map);
        List<SentMessageForm> messageListAll = new ArrayList<>();
        messageListAll.add(sentMessageForm);
        serviceUtil.sendMessage(messageListAll);
    }

    @Override
    public void scheduledRemindeMorning() throws Exception {
        Map<String, List<ScheduleEntity>> mapByTime = this.getMapByTime();
        if (mapByTime!=null||!mapByTime.isEmpty()) {
            for (String key : mapByTime.keySet()) {
                List<ScheduleEntity> scheduleEntities = mapByTime.get(key);
                if (!scheduleEntities.isEmpty()) {
                    List<String> userids = new ArrayList<>();
                    userids.add(scheduleEntities.get(0).getCreatorUserId());
                    //app端路径
                    String url = "/#";
                    String content="";
                    for (int i = 0; i < scheduleEntities.size(); i++) {
                        if (i != scheduleEntities.size() - 1) {
                            content+=scheduleEntities.get(i).getTitle()+"\n";
                        }else {
                            content+=scheduleEntities.get(i).getTitle();
                        }
                    }
                    this.sendMessage(userids, "您今日有"+scheduleEntities.size()+"个日程！", content, url);
                }
            }
        }


    }

    @Override
    public void scheduledRemindeEvery() throws Exception {
        Map<String, List<ScheduleEntity>> mapByTime = this.getMapByTime();
        if (mapByTime!=null||!mapByTime.isEmpty()) {
            for (String key : mapByTime.keySet()) {
                List<ScheduleEntity> scheduleEntities = mapByTime.get(key);
                if (!scheduleEntities.isEmpty()) {
                    for (ScheduleEntity scheduleEntity : scheduleEntities) {
                        if (DateUtil.getNowDate().getTime()-scheduleEntity.getStartTime().getTime()<=600000) {
                            List<String> userids = new ArrayList<>();
                            userids.add(scheduleEntity.getCreatorUserId());
                            //app端路径
                            String url = "/#/";
                            this.sendMessage(userids, "您有日程"+scheduleEntity.getTitle()+"快开始了", scheduleEntity.getContent(), url);
                        }
                    }
                }
            }
        }
    }


    public Map<String, List<ScheduleEntity>> getMapByTime() {
        String s = DateUtil.dateFormatToDay(DateUtil.getNowDate(), "yyyy-MM-dd");
        List<ScheduleEntity> list = this.getListByTimeScoped(s + " 00:00:00", s + " 23:59:59");
        if (!list.isEmpty()) {
            Map<String, List<ScheduleEntity>> map = list.stream().collect(Collectors.groupingBy(ScheduleEntity::getCreatorUserId));
            return map;
        }
        return null;
    }
}
